package org.linlinjava.litemall.wx.util;


import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.shiro.SecurityUtils;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.Properties;

@Intercepts(@Signature(type = Executor.class, method = "update", args = {MappedStatement.class,
        Object.class}))
public class MerchantInterceptor implements Interceptor {
    private static final Logger log = LoggerFactory.getLogger(MerchantInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object object = invocation.getArgs()[1];
        // LitemallAdmin user = (LitemallAdmin) SecurityUtils.getSubject().getPrincipal();
        String merchantId =(String) SecurityUtils.getSubject().getSession().getAttribute("X-Litemall-mchtid");
        //log.info("X-Litemall-mchtid");
        //log.info(merchantId);
        //sql类型
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        if (SqlCommandType.INSERT.equals(sqlCommandType)) {
            //插入操作时，自动插入merchantId
            Field fieldCreate = object.getClass().getDeclaredField("merchantId");
            fieldCreate.setAccessible(true);
            // 设置商户
            fieldCreate.set(object, Integer.valueOf(merchantId));
        }
        /*
        else{
            if (SqlCommandType.UPDATE.equals(sqlCommandType)) {
                //update时，自动更新merchantId
                log.info("update时，自动更新merchantId");
                log.info(object.getClass().getName());
                Field fieldUpdate = object.getClass().getDeclaredField("merchantId");
                fieldUpdate.setAccessible(true);
                // update 时应该不用设置了 fieldCreate.set(object, user.getMerchantId());
            }
        }*/
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
